<?php
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_app_class('admin','admin',0);
pc_base::load_sys_class('form','',0);

class index extends admin {
	private $db,$epaperDb;
	public $siteid;
	public $catid = 7;
	function __construct() {
        parent::__construct();
		$this->db = pc_base::load_model('epaper_upload_model');
		$this->epaperDb = pc_base::load_model('content_model');
		$this->epaperDb->set_catid($this->catid);
		$this->siteid = $this->get_siteid();
	}
	
	public function list() {
		$start_date = safe_replace($_GET['start_date']??'');
		$end_date = safe_replace($_GET['end_date']??'');
		$date = safe_replace(trim($_GET['date']??''));
		if($date)
			$date = date('Y-m-d', strtotime($date));

		$w = '';
		if($start_date)
			$w .= "`date`>='$start_date'";
		if($end_date)
			$w .= $w ? "and `date`<='$end_date'" : "`date`<='$end_date'";
		if($date)
			$w .= $w ? "and `date`='$date'" : "`date`='$date'";

		// var_dump($w);die;
		$datas = $this->db->listinfo($w,'id desc',$_GET['page']);
		$pages = $this->db->pages;
        $big_menu = array('javascript:window.top.art.dialog({id:\'add\',iframe:\'?m=epaper&c=index&a=add\', title:\'添加数字报\', width:\'780\', height:\'500\', lock:true}, function(){var d = window.top.art.dialog({id:\'add\'}).data.iframe;var form = d.document.getElementById(\'dosubmit\');form.click();return false;}, function(){window.top.art.dialog({id:\'add\'}).close()});void(0);', '添加数字报');
		include $this->admin_tpl('upload_list');
    }

	public function delete(){
		$id = (int)$_GET['id'];
		$one = $this->db->get_one(['id'=>$id]);
		if(!$one)
			showmessage('发生错误！不存在 epaper_upload:'.$id);

		$resource_dir = $one['resource_dir'];


		// 查询是否有新闻
		$one = $this->epaperDb->get_one(['date'=>$one['date']]);
		if($one){
			// 删除新闻
			$list = $this->epaperDb->select(['date'=>$one['date']],'id,catid');
			foreach($list as $val){
				$this->epaperDb->delete_content($val['id'],'',$val['catid']);
			}
		}

		// 是否在这个目录下，防止越权删除
		if(strpos($resource_dir,'uploadfile/epaper/') !== 0)
			showmessage('发生错误！资源path错误:'.$resource_dir);

		// 防止删除过多
		if($resource_dir === 'uploadfile/epaper/' || $resource_dir === 'uploadfile/epaper')
			showmessage('发生错误！资源地址错误:'.$resource_dir);
	
		// 验证是否存在目录
		// if(!file_exists($resource_dir))
		// 	showmessage('发生错误！资源不存在:'.$resource_dir);

		// 删除新闻
		// $epaperDb = pc_base::load_model('content_model');
		// $epaperDb->set_catid($this->catid);
		// $id = $epaperDb->delete(['date']);

		// 删除目录
		deleteDir($resource_dir);

		$this->db->delete(['id'=>$id]);

		showmessage(L('operation_success'));
	}

	/**
	 * 解压缩文件解析，文章入库
	 */
	public function analysis() {
		$id = (int)$_GET['id'];
		// 解析上传的文件
		try{
			$this->db->analysisCfg($id);
		}catch(Throwable $e){
			showmessage($e->getMessage());
		}

		showmessage(L('operation_success'),HTTP_REFERER);		
	}
	public function add() {

		if(isset($_POST['dosubmit'])) {
			switch($_POST['type']){
				case '手动上传':
					$id = $this->rarAdd($_POST['date']);
				break;
				case '线上抓取':
					// $_POST['date'] = '20221115';
					$date = date('Ymd', strtotime($_POST['date']));
					$id = $this->grabAdd($date);
				break;
			}
			// 解压缩文件
			// showmessage(L('operation_success'), '', '', 'add');
			echo 'ok';

		} else {
			include $this->admin_tpl('upload_add');
		}
    }

	/**
	 * epaper rar 文件解压
	 */
	private function rarAdd($date) {
		// 日期验证
		if(date("Ymd",strtotime($date)) < '19990101'){
			header("HTTP/1.0 400");
			die("请填写正确的日期：".$date);
		}
		
		//2023-03-10
		$date = date("Ymd",strtotime($date));
		// 获取上传的文件地址
		$tmp_path = $_FILES['file']['tmp_name']??null;

		if(!$tmp_path){
			header("HTTP/1.0 400");
			die("文件上传失败");
		}

		// var_dump($_FILES);


		// 直接解压rar文件
		$rar_file = rar_open($tmp_path);
		if(!$rar_file){
			header("HTTP/1.0 400");
			die("无法打开 rar 文件，请检查上传文件格式");
		}
		
		$list = rar_list($rar_file);
		if(!$list){
			header("HTTP/1.0 400");
			die("rar 解析列表失败");
		}
		
		// 提取文件名
		$rar_file_list = [];
		foreach($list as $file){
			// strtolower($file);
			$name = $file->getName();
			$rar_file_list[] = $name;
		}

		// 查找配置文件，文件名日期 *.sfv
		$publish_date = $date;
		$sfv_rar_dir = '';
		$sfv_name = '';
		$extract_path = '';

		foreach($rar_file_list as $file_name){
			if(strpos($file_name,"/") === false){
				$sfv_name = '';
				$sfv_rar_dir = $file_name;
				break;
			}
		}

		if(!$sfv_rar_dir){
			header("HTTP/1.0 400");
			die("rar文件解析失败，格式非法");
		}

		$extract_path = 'uploadfile/epaper/'.$publish_date.'/';

		if(file_exists($extract_path)){
			header("HTTP/1.0 400");
			die($extract_path.'已存在，请先删除该目录后再上传');
		}
		// 删除文件？

		mkdir($extract_path);

		foreach($rar_file_list as $file_name){
			$entry = rar_entry_get($rar_file, $file_name);
			$entry->extract($extract_path);
		}
		rar_close($rar_file);

		// 解压信息入库
		$ins = [
			'date'=> $publish_date,
			'resource_dir'=> $extract_path,
			'sfv_rar_dir'=> $sfv_rar_dir,
			'sfv_name'=> $sfv_name,
		];

		return $this->db->insert($ins,true);
	}

	/**
	 * epaper rar 文件解压 旧版
	 */
	private function rarAddOld() {
		// 获取上传的文件地址
		$tmp_path = $_FILES['file']['tmp_name']??null;
		if(!$tmp_path)
			showmessage('文件上传失败');


		// 直接解压rar文件
		$rar_file = rar_open($tmp_path) or showmessage('could not open rar');
		$list = rar_list($rar_file) or showmessage('could not get list');
		
		// 提取文件名
		$rar_file_list = [];
		foreach($list as $file){
			$rar_file_list[] = $file->getName();
		}
		// var_dump($rar_file_list);
		// die;
		// 查找配置文件，文件名日期 *.sfv
		$publish_date = '';
		$sfv_rar_dir = '';
		$sfv_name = '';
		$extract_path = '';

		foreach($rar_file_list as $file_name){
			if(substr($file_name,-4) == '.sfv'){
				$name = end(explode('/', $file_name));
				$sfv_name = $name;
				$publish_date = substr($name, 0, strlen($name)-4);
				$sfv_rar_dir = substr($file_name, 0, (strlen($file_name) - strlen($name)));
				break;
			}
		}

		if(!$publish_date)
			showmessage('sfv文件解析失败');

		$extract_path = 'uploadfile/epaper/'.$publish_date.'/';

		if(file_exists($extract_path))
			showmessage($extract_path.'已存在，请先删除该目录后再上传');
			// 删除文件？

		mkdir($extract_path);

		foreach($rar_file_list as $file_name){
			$entry = rar_entry_get($rar_file, $file_name);
			$entry->extract($extract_path);
		}
		rar_close($rar_file);

		// 解压信息入库
		$ins = [
			'date'=> $publish_date,
			'resource_dir'=> $extract_path,
			'sfv_rar_dir'=> $sfv_rar_dir,
			'sfv_name'=> $sfv_name,
		];

		return $this->db->insert($ins,true);
	}

	/**
	 * 抓取方式获取数字报数据
	 */
	public function grabAdd(string $publish_date){

		try{
			$this->db->grabAdd($publish_date);
		}catch(Throwable $e){
			header("HTTP/1.0 400");
			die($e->getMessage());
		}
	}

	/**
	 * 审核 取消审核
	 */
	public function checked(){

		$id = (int)$_GET['id'];
		$one = $this->db->get_one(['id'=>$id]);
		if(!$one)
			showmessage('发生错误！不存在 epaper_upload:'.$id);
		
		$check_status = '';
		switch($one['checked']){
			case '是':
				$check_status = '';
			break;
			case "":
				$check_status = '是';
			break;
			default:
				showmessage('发生错误！check_status 超出范围');
		}

		$one = $this->db->update(['checked'=>$check_status],['id'=>$id]);
		showmessage(L('operation_success'));
	}


	/**
	 * test
	 */
	public function test(){
		// $db = pc_base::load_model('access_token_model');
		// $rtn = $db->get_qrcode(184, 'pages/contentInfo/contentInfo','trial');
		// header("Content-type: image/jpg");
		// echo $rtn;
		// die;
		//file_put_contents('test.jpg',$rtn);
	}
}
